import datetime

from fastapi import HTTPException, Depends, APIRouter
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from starlette import status

from common.JwtUtil import JwtUtil
from common.RsaUtil import RsaUtil
from common.sqlalchemy_db import SqlalchemyX
from modules.User import User
from modules.http_resp import HttpResponse, ResponseSuccess, ResponseFail
from service.UserService import UserService


# admin123

class Token(BaseModel):
    access_token: str
    token_type: str


class LoginRequest(BaseModel):
    userName: str = None
    password: str  = None
    accessToken: str = None


router = APIRouter()
userService = UserService()


@router.post("/")
async def login(request: LoginRequest):
    async with SqlalchemyX.AsyncSessionLocal() as db:
        username = request.userName
        password = request.password
        if request.accessToken:
            data = JwtUtil.decode_access_token(request.accessToken)
            user = (await db.execute(select(User).filter(User.user_id == data.get("user_id")))).scalar()
        else:
            user = (await db.execute(select(User).filter(User.user_name == username))).scalar()
            if not user or not JwtUtil.verify_password(password, RsaUtil.sign(password)):
                return ResponseFail("用户名或密码错误",status.HTTP_401_UNAUTHORIZED)
        userBasicMes = await userService.get_user_basic_mes({"user_id": user.user_id})
        # 查看是否有这个用户
        if user:
            user.user_state = 1
            user.user_socketId = userBasicMes.get("user_socketId")
            user.user_preferSetting_id = userBasicMes.get("user_preferSetting_id")
            user.user_lastLogin_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            await db.commit()
            await db.refresh(user)
        access_token = JwtUtil.create_access_token(data={"sub": username, "user_id": user.user_id})
        return ResponseSuccess({"accessToken": access_token, "token_type": "bearer","userBasicMes": userBasicMes})
